import Axios from "axios";
import NProgress from 'nprogress'
import "nprogress/nprogress.css";
import {message,loading,closeLoading,messageBox} from '@/common/function.js'
import routers from '../router'
let service = Axios.create({
  // baseURL: import.meta.env.VITE_APP_CROSSAPI,
  baseURL: 'https://chatimi.bscd8.com/admin',
  timeout: 8000,
});
service.interceptors.request.use((config) => {
  if (config.data?.limit) {
    config.data.limit = 100
  }

    NProgress.start();
    // loading()
    let token = sessionStorage.getItem("token");
    if (token) {
      config.headers["token"] = `${token}`;
    }
    // let cookieToken = sessionStorage.getItem("cookieToken");
    // if (cookieToken) {
    //   config.headers["Cookie"] = `PHPSESSID=${cookieToken}`;
    // }
    if (!config.data) {
      config.data = {};
    }

    if (sessionStorage.getItem("login")) {
      config.data.token = sessionStorage.getItem("login");
    }

    return config;
  },
  (err) => {
    NProgress.done();
    console.log(err);
    Promise.reject(err);
  }
);
service.interceptors.response.use(
  (response) => {
    NProgress.done();
    return response.data;
  },
  async(err)  => {
    if (err.response.data.errorCode ===401) {
      await messageBox('重新登錄').then(async()=>{
          routers.push('login')
          localStorage.clear()
          sessionStorage.clear();
            })
    }
    console.log(err);
    NProgress.done();
    if (err.response) {
    await message('請求失敗,請稍後重試:  '+err.response.data.msg,'warning')
  //  await messageBox('重新登錄').then(async()=>{
  //   routers.push('login')
  //   localStorage.clear()
  //   sessionStorage.clear();
  //     })
    // return err.response.data;
    }
    return err;
  }
);

export default service;
